package cn.cellcom.agent.biz;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import cn.cellcom.agent.common.AgentEnv;
import cn.cellcom.agent.online.client.ClientManager;
import cn.cellcom.agent.online.client.VisitorClient;
import cn.cellcom.agent.pojo.TUser;
import cn.cellcom.jar.biz.AbstractFileLoadBiz;
import cn.cellcom.jar.biz.struts.CommonForm;
import cn.cellcom.jar.env.Env;
import cn.cellcom.jar.file.FU;
import cn.cellcom.jar.file.FileLoad;
import cn.cellcom.jar.file.FileProcessor;
import cn.cellcom.jar.file.IFileLoad;
import cn.cellcom.jar.file.IFileProcessor;
import cn.cellcom.jar.logon.LogonSession;
import cn.cellcom.jar.util.AU;
import cn.cellcom.jar.util.DT;
import cn.cellcom.jar.util.LogUtil;
import cn.cellcom.jar.util.MyException;

public class FileLoadBiz extends AbstractFileLoadBiz {
	private IFileProcessor ifp = new FileProcessor();

	private enum BIZ_TYPE {
		SETTING, CHAT, QUESTION
	};

	@Override
	public boolean check(CommonForm form, HttpServletRequest req) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public int delete(CommonForm cf, HttpServletRequest req) {
		String bizType = req.getParameter("bizType");
		if (BIZ_TYPE.SETTING.name().equals(bizType)) {
			LogonSession ls = new LogonSession(req);
			TUser user = (TUser) ls.getLogonObject();
			if (user == null || cf.getFileName().contains("-") && !cf.getFileName().startsWith(user.getOrg())) {
				LogUtil.i(this.getClass(), "Auth error for " + user.getOrg() + " to delete " + cf.getFieldname());
			} else {
				// 对于删除默认的文件，则不处理并返回成功:当企业处于默认图片时进行修改，同样的逻辑代码会调用删除的动作
				if (AgentEnv.DEFAULT_IMG.indexOf(cf.getFileName()) >= 0) {
					return Env.S;
				}
				try {
					ifp.delete(AgentEnv.SETTING_FILE_PATH + cf.getFileName());
					return Env.S;
				} catch (MyException e) {
					LogUtil.e(this.getClass(), "Delete file error :" + cf.getFileName());
				}
			}
		}
		return Env.E;
	}

	@Override
	public String get(HttpServletRequest request, CommonForm cf) {
		LogonSession ls = new LogonSession(request);
		String bizType = request.getParameter("bizType");
		if (BIZ_TYPE.SETTING.name().equals(bizType)) {
			try {
				return AgentEnv.SETTING_FILE_PATH + new String(cf.getFileName().getBytes("gbk"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
			}
		} else {
			String pid = null;
			TUser user = (TUser) ls.getLogonObject();
			if (user != null) {
				pid = user.getPid();
			} else {//附件必须带上pid的路径，附件的获取是在js中补充当前的pid参数，富文本中的img src是上传插入img标签的时候补充的
				pid = cf.getPid();
			}
			/*
			 * if (StringUtils.isNotBlank(cf.getId())) { VisitorClient visitor =
			 * (VisitorClient)
			 * ClientManager.getInstance().getClient(cf.getId()); org =
			 * visitor.getOrg(); } else
			 */
			if (BIZ_TYPE.QUESTION.name().equals(bizType)) {// FAQ问答的内容
				return AgentEnv.QUESTION_FILE_PATH + pid + "/" + cf.getFileName();
			} else if (BIZ_TYPE.CHAT.name().equals(bizType)) {
				return AgentEnv.CHAT_FILE_PATH + pid + "/" + cf.getFileName();
			}
		}
		return null;
	}

	@Override
	public Map<String, Object> upload(HttpServletRequest request, CommonForm form) {
		Map<String, Object> map = new HashMap<String, Object>();
		String result[] = null;
		CommonForm cf = (CommonForm) form;
		LogonSession ls = new LogonSession(request);

		String bizType = request.getParameter("bizType");
		String multiType = request.getParameter("multiType");
		if (BIZ_TYPE.SETTING.name().equals(bizType)) {
			TUser user = (TUser) ls.getLogonObject();
			if (user != null) {
				result = user.getSettingFile(cf.getFile().getFileName());
			} else {
				map.put("code", Env.E);
			}
		} else if (BIZ_TYPE.QUESTION.name().equals(bizType)) {// FAQ问答的内容
			TUser user = (TUser) ls.getLogonObject();
			if (user != null) {
				result = user.getSelfQuestionFile(cf.getFile().getFileName());

				Set<String> questionTempSet = (Set<String>) request.getSession().getAttribute("questionTempSet");
				if (questionTempSet == null) {
					questionTempSet = new HashSet<String>();
					request.getSession().setAttribute("questionTempSet", questionTempSet);
				}
				questionTempSet.add(result[0]);
			} else {
				map.put("code", Env.E);
			}
		} else if (BIZ_TYPE.CHAT.name().equals(bizType)) {
			if (StringUtils.isNotBlank(cf.getId())) {
				VisitorClient visitor = (VisitorClient) ClientManager.getInstance().getClient(cf.getId());
				if (visitor != null) {
					result = visitor.getCrm().getChatFile(cf.getFile().getFileName(), multiType);
				} else {
					map.put("code", Env.E);
				}
			} else {
				TUser user = (TUser) ls.getLogonObject();
				if (user != null) {
					result = user.getChatFile(cf.getFile().getFileName(), multiType);
				} else {
					map.put("code", Env.E);
				}
			}
			map.put("date", DT.getYYYYMMDD());
			map.put("overdue", DT.getYYYYMMDDHHMMSS(DT.getNextDay(7)));
		}
		if (result != null) {
			IFileLoad load = new FileLoad();
			try {
				load.uploadToFile(cf.getFile(), result[1]);

				if (AU.isExist(FU.IMAGE, FU.getSuffix(result[1]).toLowerCase(), null) >= 0) {
					try {
						BufferedImage bufferedImage;
						bufferedImage = ImageIO.read(new File(result[1]));
						int width = bufferedImage.getWidth();
						int height = bufferedImage.getHeight();
						map.put("width", width);
						map.put("height", height);
					} catch (IOException e) {
					}
				}

				map.put("code", Env.S);
				map.put("newName", result[0]);
				map.put("oldName", cf.getFile().getFileName());
				map.put("size", cf.getFile().getFileSize());
			} catch (MyException e) {
				LogUtil.e(this.getClass(), "Upload fail for " + cf.getFile().getFileName(), e);
				map.put("code", Env.E);
			}
		} else {

		}
		return map;
	}

	/**
	 * 对于question配置的文件,如果确认报错了则需要从request中移除这个文件,否则将在destory的时候被删除
	 * 
	 * @param req
	 * @param file
	 */
	public static void confirmTheQuestionFile(HttpServletRequest request, String file) {
		Set<String> questionTempSet = (Set<String>) request.getSession().getAttribute("questionTempSet");
		if (questionTempSet != null) {
			questionTempSet.remove(file);
		}
	}

	/**
	 * 没有实际保存问答题,因此删除文件
	 * 
	 * @param ss
	 * @param user2
	 * @param file
	 */
	public static void destoryTheQuestionFile(HttpSession ss, TUser user2) {
		Set<String> questionTempSet = (Set<String>) ss.getAttribute("questionTempSet");
		if (questionTempSet != null) {
			IFileProcessor ifp = new FileProcessor();
			for (String one : questionTempSet) {
				try {
					String file = AgentEnv.QUESTION_FILE_PATH + user2.getPid() + "/" + one;
					boolean b = ifp.delete(file);
					LogUtil.i(FileLoadBiz.class, "Delete the question file for abandend :" + file + ", result is " + b);
				} catch (MyException e) {
					LogUtil.e(FileLoadBiz.class, "Delete file error :" + one);
				}
			}
		}
	}

	public static void destoryTheQuestionFile(String file, TUser user2) {
		IFileProcessor ifp = new FileProcessor();
		try {
			boolean b = ifp.delete(AgentEnv.QUESTION_FILE_PATH + user2.getPid() + "/" + file);
			LogUtil.i(FileLoadBiz.class, "Delete the question file for replaced :" + file + ", result is " + b);
		} catch (MyException e) {
			LogUtil.e(FileLoadBiz.class, "Delete file error :" + file);
		}
	}

}
